package logging;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/*
 * LogWriter class handles logging output to the screen and a log file.
 * It also handles sending text through an output stream to a client
 * while logging the text sent.
 */
public class LogWriter {
	private DateStamp date = new DateStamp();
	private int threadID = -1;
	private PrintWriter writer;
	private String logFileName = "server.log";

	public LogWriter() {
	}

	public LogWriter(int id) {
		threadID = id;
	}

	public int getThreadID(int id) {
		return threadID;
	}

	public PrintWriter getWriter() {
		return writer;
	}

	public void setThreadID(int id) {
		threadID = id;
	}

	public void setWriter(PrintWriter out) {
		writer = out;
	}

	// Standard log output to screen and log file.
	public synchronized void log(String output) {
		System.out.println(date.stamp() + "(tID:" + threadID + ") -> " + output);
		writeToFile(output);
	}

	// Sends output to client and logs output to the screen and log file.
	public void sendToClient(String output) {
		writer.println(output);
		log("(Sending) " + output);
	}

	// Sends output to a log file.
	private void writeToFile(String output) {
		try {
			File file = new File(logFileName);
			FileWriter logFile = new FileWriter(file, true);

			logFile.write(date.stamp() + "(tID:" + threadID + ") -> " + output + "\n");
			logFile.flush();
			logFile.close();
		} catch (IOException e) {
			log("Error writing to log file!");
		}
	}
}
